package com.github.shiqiyue.app.config.session;

import org.springframework.session.web.http.CookieHttpSessionIdResolver;
import org.springframework.session.web.http.HttpSessionIdResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

public class MultiHttpSessionIdResolver implements HttpSessionIdResolver {

    List<UrlMatchHttpSessionIdResolver> urlMatchHttpSessionIdResolvers = new ArrayList<>();

    private CookieHttpSessionIdResolver defaultHttpSessionIdResolver = new CookieHttpSessionIdResolver();

    /****
     * 添加httpsession id resolver
     * @param urlMatchHttpSessionIdResolver
     */
    public void addHttpSessionIdResolver(UrlMatchHttpSessionIdResolver urlMatchHttpSessionIdResolver) {
        urlMatchHttpSessionIdResolvers.add(urlMatchHttpSessionIdResolver);
    }


    @Override
    public List<String> resolveSessionIds(HttpServletRequest request) {
        String servletPath = request.getServletPath();
        for (UrlMatchHttpSessionIdResolver urlMatchHttpSessionIdResolver : urlMatchHttpSessionIdResolvers) {
            if (urlMatchHttpSessionIdResolver.match(servletPath)) {
                return urlMatchHttpSessionIdResolver.resolveSessionIds(request);
            }
        }
        return defaultHttpSessionIdResolver.resolveSessionIds(request);
    }

    @Override
    public void setSessionId(HttpServletRequest request, HttpServletResponse response, String sessionId) {
        String servletPath = request.getServletPath();
        for (UrlMatchHttpSessionIdResolver urlMatchHttpSessionIdResolver : urlMatchHttpSessionIdResolvers) {
            if (urlMatchHttpSessionIdResolver.match(servletPath)) {
                urlMatchHttpSessionIdResolver.setSessionId(request, response, sessionId);
                return;
            }
        }
        defaultHttpSessionIdResolver.setSessionId(request, response, sessionId);
    }

    @Override
    public void expireSession(HttpServletRequest request, HttpServletResponse response) {
        String servletPath = request.getServletPath();
        for (UrlMatchHttpSessionIdResolver urlMatchHttpSessionIdResolver : urlMatchHttpSessionIdResolvers) {
            if (urlMatchHttpSessionIdResolver.match(servletPath)) {
                urlMatchHttpSessionIdResolver.expireSession(request, response);
                return;
            }
        }
        defaultHttpSessionIdResolver.expireSession(request, response);
    }
}
